package com.wechat.DAO.DaoImpl;

import com.wechat.DAO.MessageDAO;
import com.wechat.pojo.Message;
import com.wechat.pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MessageDAOIpml implements MessageDAO {
    Connection connection = null;
    PreparedStatement pst = null;
    ResultSet resultSet = null;
    @Override
    public Message query(long M_Time) {
        Message message = null;
        try {
            System.out.println(M_Time);
            Class.forName("com.mysql.jdbc.Driver");
            connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/wechat?useSSL=false", "root", "123456");
            PreparedStatement pst = connection.prepareStatement("SELECT * FROM USER_MESSAGES WHERE M_TIME=?");
            pst.setString(1,String.valueOf(M_Time));
            resultSet = pst.executeQuery();
            while (resultSet.next()){
                message = new Message(resultSet.getLong(1),
                        resultSet.getString(2),
                        resultSet.getString(3),
                        resultSet.getInt(4),
                        resultSet.getString(5),
                        resultSet.getBoolean(6),
                        resultSet.getBoolean(7));
            }
            System.out.println(message);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            closeAll();
        }
        return message;
    }


    @Override
    public Boolean add(Message message) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/wechat?useSSL=false", "root", "123456");
            PreparedStatement pst = connection.prepareStatement("INSERT INTO USER_MESSAGES VALUE (?,?,?,?,?,?,?)");
            pst.setLong(1,message.getM_Time());
            pst.setString(2,message.getRID());
            pst.setString(3,message.getSID());
            pst.setInt(4,message.getM_Type());
            pst.setString(5,message.getM_Content());
            pst.setBoolean(6,message.getIF_Send());
            pst.setBoolean(7,message.getIF_Receive());
            pst.execute();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            closeAll();
        }
        return true;
    }

    @Override
    public Boolean sendOk(long M_Time) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/wechat?useSSL=false", "root", "123456");
            PreparedStatement pst = connection.prepareStatement("UPDATE USER_MESSAGES SET IF_Send=? WHERE M_Time=?");
            pst.setBoolean(1,true);
            pst.setLong(2,M_Time);
            pst.execute();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            closeAll();
        }
        return true;
    }

    @Override
    public Boolean receiveOk(long M_Time) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/wechat?useSSL=false", "root", "123456");
            PreparedStatement pst = connection.prepareStatement("UPDATE USER_MESSAGES SET IF_Receive=? WHERE M_Time=?");
            pst.setBoolean(1,true);
            pst.setLong(2,M_Time);
            pst.execute();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            closeAll();
        }
        return true;
    }

    @Override
    public Boolean delete(Message message) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/wechat?useSSL=false", "root", "123456");
            PreparedStatement pst = connection.prepareStatement("DELETE FROM USER_MESSAGES WHERE M_TIME=?");
            pst.setLong(1,message.getM_Time());
            pst.execute();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            closeAll();
        }
        return true;
    }

    @Override
    public Boolean deleteByTime(Long M_Time) {
        Message message;
        if((message = query(M_Time)) != null){
            if(delete(message)){
                return true;
            }
        }
        return false;
    }

    //核心代码！！！客户端查询消息，接收者是自己就行
    public List<Message> getNewMessagesByUsername(String username){
        List<Message> messages = new ArrayList<>();
        try{
            Class.forName("com.mysql.jdbc.Driver");
            connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/wechat?useSSL=false", "root", "123456");
            PreparedStatement pst = connection.prepareStatement("SELECT * FROM USER_MESSAGES WHERE RID=? AND IF_Receive=0");
            pst.setString(1,username);
            resultSet = pst.executeQuery();
            while (resultSet.next()){
                Boolean IF_Send = resultSet.getBoolean(6);
                Boolean IF_Receive = resultSet.getBoolean(7);
                if(IF_Receive){//如果这条消息已经被接收,那么跳过，超过15天会被删除，但是期间如果使用恢复云端数据时，可以通过getAllMessagesByUsername获取
                    continue;
                }
                if(!IF_Send){//如果这条消息还没成功发送，那么跳过这条消息（这个功能之后可改进作为撤回功能），这里不作处理跳过
                    //如果想做撤回功能，给接收端再发个callBack（携带时间戳）让它从数据库删除
                    continue;
                }
                long M_Time = resultSet.getLong(1); //主键
                int M_Type = resultSet.getInt(4); //消息种类
                String RID = resultSet.getString(2);
                String SID = resultSet.getString(3);
                String M_Content = resultSet.getString(5);

                Message message = new Message(M_Time,RID,SID,M_Type,M_Content,true,false);
                messages.add(message);  //加入消息列表返回
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll();
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return messages;
    }

    //用于恢复云端备份数据
    @Override
    public List<Message> getAllMessagesByUsername(String username){
        List<Message> messages = new ArrayList<>();
        try{
            Class.forName("com.mysql.jdbc.Driver");
            connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/wechat?useSSL=false", "root", "123456");
            PreparedStatement pst = connection.prepareStatement("SELECT * FROM USER_MESSAGES WHERE RID=? OR SID=?");
            pst.setString(1,username);
            pst.setString(2,username);
            resultSet = pst.executeQuery();
            while (resultSet.next()){
                Boolean IF_Send = resultSet.getBoolean(6);
                Boolean IF_Receive = resultSet.getBoolean(7);
                if(!IF_Send){//如果这条消息还没成功发送，那么跳过这条消息（这个功能之后可改进作为撤回功能），这里不作处理跳过
                    //如果想做撤回功能，给接收端再发个callBack（携带时间戳）让它从数据库删除
                    continue;
                }
                long M_Time = resultSet.getLong(1); //主键
                int M_Type = resultSet.getInt(4); //消息种类
                String RID = resultSet.getString(2);
                String SID = resultSet.getString(3);
                String M_Content = resultSet.getString(5);

                Message message = new Message(M_Time,RID,SID,M_Type,M_Content,IF_Send,IF_Receive);
                messages.add(message);  //加入消息列表返回
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll();
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return messages;
    }



    private void closeAll() {
        if(pst!=null){
            try {
                pst.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
